package com.gensdai.leliang.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gensdai.leliang.R;
import com.gensdai.leliang.base.BaseActivityNoAbs;
import com.gensdai.leliang.dialog.Upload;
import com.gensdai.leliang.entity.User;
import com.gensdai.leliang.entity.UserNameBean;
import com.gensdai.leliang.json_base.json_base;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.trello.rxlifecycle2.android.ActivityEvent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/9/7.
 */

public class Set_social extends BaseActivityNoAbs implements View.OnClickListener {
    @BindView(R.id.ui_title)
    TextView uiTitle;
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.weixin_state)
    TextView weixinState;
    @BindView(R.id.qq_state)
    TextView qqState;
    @BindView(R.id.data)
    TextView data;
    @BindView(R.id.q)
    TextView q;
    @BindView(R.id.j)
    TextView j;
    @BindView(R.id.set)
    LinearLayout set;
    @BindView(R.id.set_weixin)
    LinearLayout setWeixin;
    @BindView(R.id.set_qq)
    LinearLayout setQq;

    private Upload up;
    SharedPreferences share;
    SharedPreferences.Editor ed;

    private boolean ceshu = true;

    private String QQ_APP_ID = "1106232764";
    private String WX_APP_ID = "wx701d441207f210af";
    private String SCOPE = "all"; //获取信息的范围参数
    private Tencent mTencent; //qq主操作对象
    private IUiListener loginListener; //授权登录监听器
    private IUiListener userInfoListener; //获取用户信息监听器
    private UserInfo userInfo; //qq用户信息
    private IWXAPI api;
    private String openID = "";
    private String accessToken;
    private String expires;
    private UserNameBean user;
    private int jiechuState = 0;

    private final int ENTER = 1;//查询
    private final int BANGDING = 2;// 绑定
    private final int JIECHU = 3;// 解除
    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case ENTER:
                    up.dismiss();
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {
                            user = (UserNameBean) new json_base().JsonDSF(new JSONObject((String) msg.obj));
                            qqState.setText(user.getIfBindQQ());
                            weixinState.setText(user.getIfBindWeChat());
                        } else {
                            Toast.makeText(
                                    Set_social.this,
                                    new JSONObject((String) msg.obj)
                                            .getString("message"),
                                    Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case BANGDING:
                    up.dismiss();
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {
                            Query();
                        } else {
                            Toast.makeText(
                                    Set_social.this,
                                    new JSONObject((String) msg.obj)
                                            .getString("message"),
                                    Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case JIECHU:
                    up.dismiss();
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {
                            Query();
                        } else {
                            Toast.makeText(
                                    Set_social.this,
                                    new JSONObject((String) msg.obj)
                                            .getString("message"),
                                    Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_set_social);
        ButterKnife.bind(this);
        init();
        Query();
    }

    /**
     * 初始化
     */
    private void init() {

        uiTitle.setText("社交帐号绑定");
        share = getSharedPreferences("User", MODE_PRIVATE);
        ed = share.edit();
        up = new Upload(this);

        initWX();
        initQqLogin();

        back.setOnClickListener(this);
        setWeixin.setOnClickListener(this);
        setQq.setOnClickListener(this);
        q.setOnClickListener(this);
        j.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                this.finish();
                break;
            case R.id.set_weixin:
                if (weixinState.getText().toString().trim().equals("未绑定")) {
                    SendAuth.Req req = new SendAuth.Req();
                    req.scope = "snsapi_userinfo";
                    req.state = "wechat_sdk_demo_test";
                    api.sendReq(req);
                    this.finish();
                } else {
                    set.setVisibility(View.VISIBLE);
                    data.setText("要解除与微信帐号的绑定吗");
                    jiechuState = 1;
                }
                break;
            case R.id.set_qq:
                if (qqState.getText().toString().trim().equals("未绑定")) {
                    ceshu = true;
                    mTencent.login(this, SCOPE, loginListener);
                } else {
                    set.setVisibility(View.VISIBLE);
                    data.setText("要解除与QQ帐号的绑定吗");
                    jiechuState = 2;
                }
                break;
            case R.id.q:
                set.setVisibility(View.GONE);
                break;
            case R.id.j:
                if (jiechuState == 1) {
                    jiechu("1");
                } else {
                    jiechu("2");
                }
                set.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    /**
     * 查询绑定状态
     */
    private void Query() {
        //获取edit的值后请求

        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("userId", share.getString("user_id", ""));
        toStr(loginParams);
    }

    //返回字符串类型
    private void toStr(Map<String, String> loginParams) {
        up.show();
        ApiService.getInstance(this).QUERY_THIRDPARTY_STATE(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = ENTER;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        up.dismiss();
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }


    /**
     * 解除绑定状态
     */
    private void jiechu(String state) {
        //获取edit的值后请求

        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("userId", share.getString("user_id", ""));
        loginParams.put("unbound", state);//“1”:解除微信绑定 “2”：解除QQ绑定
        jiechutoStr(loginParams);
    }

    //返回字符串类型
    private void jiechutoStr(Map<String, String> loginParams) {
        up.show();
        ApiService.getInstance(this).REMOVE_THIRDPARTY_BIND(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = JIECHU;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        up.dismiss();
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }

    //初始化微信，获取实例
    private void initWX() {
        api = WXAPIFactory.createWXAPI(this, WX_APP_ID, false);
        api.registerApp(WX_APP_ID);

    }


    //初始化QQ登录分享的需要的资源
    private void initQqLogin() {
        mTencent = Tencent.createInstance(QQ_APP_ID, this);
        //创建QQ登录回调接口
        loginListener = new IUiListener() {
            @Override
            public void onComplete(Object value) {
                //登录成功后回调该方法
//                Toast.makeText(user_enter.this, "登录成功", Toast.LENGTH_SHORT).show();
                System.out.println("有数据返回..");
                if (value == null) {
                    return;
                }

                try {
                    JSONObject jo = (JSONObject) value;

                    int ret = jo.getInt("ret");

//                    System.out.println("json=" + String.valueOf(jo));

                    if (ret == 0) {
//                        Toast.makeText(user_enter.this, "登录成功",
//                                Toast.LENGTH_SHORT).show();

                        openID = jo.getString("openid");
                        accessToken = jo.getString("access_token");
                        expires = jo.getString("expires_in");

                        Map<String, String> loginParams = new HashMap<>();
                        loginParams.put("qqId", openID);   //QQ标识
                        loginParams.put("userId", share.getString("user_id", ""));
                        Log.e("QQ标识：", openID);
                        if (ceshu) {
                            ceshu = false;
                            bangdingtoStr(loginParams);
                        }


                    }

                } catch (
                        Exception e)

                {
                    // TODO: handle exception
                }

            }

            @Override
            public void onError(UiError uiError) {
                //登录失败后回调该方法
                Toast.makeText(Set_social.this, "登录失败", Toast.LENGTH_SHORT).show();
                Log.e("LoginError:", uiError.toString());
            }

            @Override
            public void onCancel() {
                //取消登录后回调该方法
                Toast.makeText(Set_social.this, "取消登录", Toast.LENGTH_SHORT).show();
            }
        }

        ;
    }

    //返回字符串类型
    private void bangdingtoStr(Map<String, String> loginParams) {
        up.show();
        ApiService.getInstance(this).BIND_THIRDPARTY_DIRECTILY(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = BANGDING;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        up.dismiss();
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//  官方文档上面的是错误的
//        if(requestCode == Constants.REQUEST_API) {
//            if(resultCode == Constants.RESULT_LOGIN) {
//                mTencent.handleLoginData(data, loginListener);
//            }
//  resultCode 是log出来的，官方文档里给的那个属性是没有的

        if (requestCode == Constants.REQUEST_LOGIN) {
            if (resultCode == -1) {
                Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
                Tencent.handleResultData(data, loginListener);
            }
        }
    }

}
